import os.path
import uuid

from fastapi import UploadFile

import api.repository.knowledgebase_item_repository as knowledgebase_item_repository
from api.model.knowledgebase_item_model import KnowledgebaseItem
from api.model.knowledgebase_model import Knowledgebase
from api.vo.ResponseVo import ResponseVo, ResponsePageVo
from api.vo.form.knowledge_form import KnowledgebaseForm
from api.vo.form.knowledge_item_form import KnowledgebaseItemForm
from api.vo.query.knowledgebase_item_query import KnowledgebaseItemQuery
from api.vo.query.knowledgebase_query import KnowledgebaseQuery
from config.configs import FILE_PATH

def disabled(idList: list) -> ResponseVo:
    return ResponseVo(data=knowledgebase_item_repository.update_status(idList=idList, status="0"))


def enabled(idList: list) -> ResponseVo:
    return ResponseVo(data=knowledgebase_item_repository.update_status(idList=idList, status="1"))


def list(knowledgebaseItemQuery: KnowledgebaseItemQuery) -> ResponsePageVo:
    list,count = knowledgebase_item_repository.list(knowledgebaseItemQuery=knowledgebaseItemQuery)
    return ResponsePageVo(data=list, total=count, page=knowledgebaseItemQuery.page, rows=knowledgebaseItemQuery.rows)


def deletes(idList: list) -> ResponseVo:
    return ResponseVo(data=knowledgebase_item_repository.delete(idList = idList))


def get(id):
    return ResponseVo(data=knowledgebase_item_repository.get(id=id))


async def add(file: UploadFile, kb_id: str):
    item = KnowledgebaseItem()
    item.kb_id = kb_id
    item.id = str(uuid.uuid4())
    item.location=f'{FILE_PATH}/{item.id}/{file.filename}'
    item.source_type = "local"
    item.type = file.content_type
    item.name = file.filename
    item.size = file.size
    file_content = await file.read()  # 读取文件
    if not os.path.exists(f'{FILE_PATH}/{item.id}/'):
        os.makedirs(f'{FILE_PATH}/{item.id}/')
    with open(item.location, "wb") as f:
        f.write(file_content)
    return knowledgebase_item_repository.add(item)